package com.abss.vote.controller;

import com.abss.vote.model.MpInfo;
import com.abss.vote.model.MyProps;
import com.abss.vote.service.UserReceptionService;
import com.abss.vote.util.Utils;
import com.abss.vote.util.WxShare;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信JSSDK
 */
@Controller
@ResponseBody
public class WeChatHander {

    @Autowired
    private UserReceptionService userReceptionService;


    @Autowired
    private MyProps myProps;

    //微信自定义分享
    @RequestMapping("/share")
    public Object share(String URL){

        //将服务器信息添加到session中
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());

//        try {
//            List<String> ls= FileUtils.getBanner();//获取配置文件中的数据
//            mp.setSERVER_ID(ls.get(0));
//            mp.setSERVER_NAME(ls.get(1));
//            mp.setMP_APP_ID(ls.get(2));
//            mp.setMP_APP_SECRET(ls.get(3));
//            mp.setWXCALLBACK(ls.get(4));
//        }catch (Exception e){
//            e.printStackTrace();
//        }


        String url="";
        //需要转换解码url
        try {
            url = java.net.URLDecoder.decode(URL,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //从数据库获取access_token和access_ticket
//        MpInfo mpInfo=userReceptionService.getMpInFo(mp.getSERVER_ID());
        //获取最后更新时间
        Date last = mp.getLAST_UPDATE_TIME();
        //获取7200s前时间点
        Date two = Utils.gettwoDate();

        String aeecss_ticket=mp.getAEECSS_TICKET();
        String aeecss_token=mp.getACCESS_TOKEN();
        if(last.before(two)){//请求微信获取新信息   两边都没更新
            aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());

            //将数据存入数据库
            MpInfo mpInfo1=new MpInfo();
            mpInfo1.setACCESS_TOKEN(aeecss_token);
            mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
            mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
            userReceptionService.setMpInFo(mpInfo1);
            mp.setACCESS_TOKEN(aeecss_token);


            aeecss_ticket = WxShare.getAccess_ticket(mp.getACCESS_TOKEN());

            //将数据存入数据库
            MpInfo mpInfo2=new MpInfo();
            mpInfo2.setAEECSS_TICKET(aeecss_ticket);
            mpInfo2.setMP_APP_ID(mp.getMP_APP_ID());
            mpInfo2.setMP_APP_SECRET(mp.getMP_APP_SECRET());
            userReceptionService.setMpInFoticket(mpInfo2);
            mp.setAEECSS_TICKET(aeecss_ticket);

        }else {//token在朗读亭已更新状态

            Date ticketTime = mp.getTICKET_LAST_UPDATE_TIME();
            if (ticketTime.before(last)) {//请求微信获取新信息
                aeecss_ticket = WxShare.getAccess_ticket(mp.getACCESS_TOKEN());

                //将数据存入数据库
                MpInfo mpInfo1 = new MpInfo();
                mpInfo1.setAEECSS_TICKET(aeecss_ticket);
                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
                userReceptionService.setMpInFoticket(mpInfo1);
                mp.setAEECSS_TICKET(aeecss_ticket);
            }
        }

        //3、时间戳和随机字符串
        String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
        //4、获取url
        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket="+aeecss_ticket+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;
        //6、将字符串进行sha1加密
        String signature =WxShare.SHA1(str);
        //System.out.println("参数："+str+"\n签名："+signature);
        Map<String,String> map=new HashMap<>();
        map.put("appId",mp.getMP_APP_ID());
        map.put("timestamp",timestamp);
        map.put("accessToken",aeecss_token);
        map.put("ticket",aeecss_ticket);
        map.put("nonceStr",nonceStr);
        map.put("signature",signature);
        return map;
    }

    //录音jssdk
    @RequestMapping("/git_record")
    public Object git_record(@RequestParam(required=false,defaultValue="1") String action,
                             @RequestParam(required=false,defaultValue="1") String url,
                             @RequestParam(required=false,defaultValue="1") String mediaID){
        Map<String,Object> ha = new HashMap<>();
        //将服务器信息添加到session中
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
//        try {
//            List<String> ls= FileUtils.getBanner();//获取配置文件中的数据
//            mp.setSERVER_ID(ls.get(0));
//            mp.setSERVER_NAME(ls.get(1));
//            mp.setMP_APP_ID(ls.get(2));
//            mp.setMP_APP_SECRET(ls.get(3));
//            mp.setWXCALLBACK(ls.get(4));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        Map<String, String> map = new HashMap<>();
        if(action.equals("sign")) {
            //需要转换解码url
            try {
                url = java.net.URLDecoder.decode(url, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            //从数据库获取access_token和access_ticket
//            MpInfo mpInfo = userReceptionService.getMpInFo(mp.getSERVER_ID());
            //获取最后更新时间
            Date last = mp.getLAST_UPDATE_TIME();
            //获取7200s前时间点
            Date two = Utils.gettwoDate();



//            String aeecss_token = null;
//            String aeecss_ticket = null;
//            if (last.before(two)) {//请求微信获取新信息
//                aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());
//                aeecss_ticket = WxShare.getAccess_ticket(aeecss_token);
//                //将数据存入数据库
//                MpInfo mpInfo1 = new MpInfo();
//                mpInfo1.setACCESS_TOKEN(aeecss_token);
//                mpInfo1.setAEECSS_TICKET(aeecss_ticket);
//                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
//                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
//                userReceptionService.setMpInFo(mpInfo1);
//            } else {//数据库取值
//                aeecss_token = mp.getACCESS_TOKEN();
//                aeecss_ticket = mp.getAEECSS_TICKET();
//            }

//            String aeecss_token=null;
//            if(last.before(two)){//请求微信获取新信息
//                aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());
//
//                //将数据存入数据库
//                MpInfo mpInfo1=new MpInfo();
//                mpInfo1.setACCESS_TOKEN(aeecss_token);
//                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
//                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
//                userReceptionService.setMpInFo(mpInfo1);
//                mp.setACCESS_TOKEN(aeecss_token);
//            }
//
//            String aeecss_ticket=null;
//            Date ticketTime = mp.getTICKET_LAST_UPDATE_TIME();
//            if(ticketTime.before(two)) {//请求微信获取新信息
//                aeecss_ticket = WxShare.getAccess_ticket(mp.getACCESS_TOKEN());
//
//                //将数据存入数据库
//                MpInfo mpInfo1=new MpInfo();
//                mpInfo1.setAEECSS_TICKET(aeecss_ticket);
//                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
//                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
//                userReceptionService.setMpInFoticket(mpInfo1);
//                mp.setAEECSS_TICKET(aeecss_ticket);
//            }


            String aeecss_ticket=mp.getAEECSS_TICKET();
            String aeecss_token=mp.getACCESS_TOKEN();
            if(last.before(two)){//请求微信获取新信息   两边都没更新
                aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());

                //将数据存入数据库
                MpInfo mpInfo1=new MpInfo();
                mpInfo1.setACCESS_TOKEN(aeecss_token);
                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
                userReceptionService.setMpInFo(mpInfo1);
                mp.setACCESS_TOKEN(aeecss_token);


                aeecss_ticket = WxShare.getAccess_ticket(mp.getACCESS_TOKEN());

                //将数据存入数据库
                MpInfo mpInfo2=new MpInfo();
                mpInfo2.setAEECSS_TICKET(aeecss_ticket);
                mpInfo2.setMP_APP_ID(mp.getMP_APP_ID());
                mpInfo2.setMP_APP_SECRET(mp.getMP_APP_SECRET());
                userReceptionService.setMpInFoticket(mpInfo2);
                mp.setAEECSS_TICKET(aeecss_ticket);

            }else {//token在朗读亭已更新状态

                Date ticketTime = mp.getTICKET_LAST_UPDATE_TIME();
                if (ticketTime.before(last)) {//请求微信获取新信息
                    aeecss_ticket = WxShare.getAccess_ticket(mp.getACCESS_TOKEN());

                    //将数据存入数据库
                    MpInfo mpInfo1 = new MpInfo();
                    mpInfo1.setAEECSS_TICKET(aeecss_ticket);
                    mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
                    mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
                    userReceptionService.setMpInFoticket(mpInfo1);
                    mp.setAEECSS_TICKET(aeecss_ticket);
                }
            }


            //3、时间戳和随机字符串
            String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
            //4、获取url
            //5、将参数排序并拼接字符串
            String str = "jsapi_ticket=" + aeecss_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
            //6、将字符串进行sha1加密
            String signature = WxShare.SHA1(str);
            //System.out.println("参数："+str+"\n签名："+signature);
            ha.put("c","0");
            ha.put("m","请求成功！");
            map.put("appid", mp.getMP_APP_ID());
            map.put("timestamp", timestamp);
            map.put("noncestr", nonceStr);
            map.put("signature", signature);
            ha.put("v",map);
        }else if(action.equals("wxdown")){
            //从数据库获取access_token和access_ticket
            MpInfo mpInfo = userReceptionService.getMpInFo(mp.getSERVER_ID());
            //获取最后更新时间
            Date last = mpInfo.getLAST_UPDATE_TIME();
            //获取7200s前时间点
            Date two = Utils.gettwoDate();
//            String aeecss_token = null;
//            String aeecss_ticket = null;
//            if (last.before(two)) {//请求微信获取新信息
//                aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());
//                aeecss_ticket = WxShare.getAccess_ticket(aeecss_token);
//                //将数据存入数据库
//                MpInfo mpInfo1 = new MpInfo();
//                mpInfo1.setACCESS_TOKEN(aeecss_token);
//                mpInfo1.setAEECSS_TICKET(aeecss_ticket);
//                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
//                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
//                userReceptionService.setMpInFo(mpInfo1);
//            } else {//数据库取值
//                aeecss_token = mpInfo.getACCESS_TOKEN();
//            }

            String aeecss_token=mp.getACCESS_TOKEN();
            if(last.before(two)){//请求微信获取新信息
                aeecss_token = WxShare.getAccess_token(mp.getMP_APP_ID(), mp.getMP_APP_SECRET());

                //将数据存入数据库
                MpInfo mpInfo1=new MpInfo();
                mpInfo1.setACCESS_TOKEN(aeecss_token);
                mpInfo1.setMP_APP_ID(mp.getMP_APP_ID());
                mpInfo1.setMP_APP_SECRET(mp.getMP_APP_SECRET());
                userReceptionService.setMpInFo(mpInfo1);
                mp.setACCESS_TOKEN(aeecss_token);
            }



            String urls = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + aeecss_token + "&media_id=" + mediaID;
            try {
                OutputStreamWriter opsw = null;

                URL u = new URL(urls);
                java.net.HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("GET");
                //设置是否允许数据写入(允许),因为要写随机数
                connection.setDoInput(true);
                //是否允许输出(允许)
                connection.setDoOutput(true);
                //设置连接响应时间
                connection.setConnectTimeout(5000);
                //设置参数读取时间
                connection.setReadTimeout(10000);
                //设置请求头
                connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                //提交请求
                opsw = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                opsw.flush();

                InputStream is=connection.getInputStream();
                byte[] buff2=new byte[1024*1024*4];
                byte[] buff=new byte[1024*1024];
                int offset=0;
                int len=0;
                while ((len=is.read(buff)) !=-1) {
                    System.arraycopy(buff,0,buff2,offset,len);
                    offset+=len;
                }

                byte[] result=new byte[offset];
                System.arraycopy(buff2,0,result,0,offset);

                JSONObject ret=getJSONObject(result);
                if(ret!=null){

                    ha.put("c","2");
                    ha.put("m",ret.get("errcode")+":"+ret.get("errmsg"));
                }else{
                    ha.put("c","0");
                    ha.put("m","请求成功！");
                    map.put("mime","audio/amr");
                    map.put("data", Base64.getEncoder().encodeToString(result));
                    ha.put("v",map);
                }
            } catch (IOException e) {
                e.printStackTrace();
                ha.put("c","1");
                ha.put("m","请求失败···");
            }
        }
        return ha;
    }

    private JSONObject getJSONObject(byte[] ret){

        try {
            String str=new String(ret,"utf-8");
            return new JSONObject(str);
            //return str.contains("errcode");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //


    }

}
